package cn.kz.hrm.service.impl;

import cn.kz.hrm.domain.Employee;
import cn.kz.hrm.domain.Tenant;
import cn.kz.hrm.dto.TenantRegisterDto;
import cn.kz.hrm.mapper.EmployeeMapper;
import cn.kz.hrm.mapper.TenantMapper;
import cn.kz.hrm.service.ITenantService;
import cn.kz.hrm.util.encrypt.MD5;
import com.alibaba.druid.sql.visitor.functions.Now;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author kz
 * @since 2020-06-27
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {
//1普通员工 ，2客服人员，3租户管理员，4平台管理员
    public static final Integer TYPE_GENERAL_STAFF = 1;
    public static final Integer TYPE_CUSTOMER_SERVICE = 2;
    public static final Integer TYPE_TENANT_ADMIN= 3;
    public static final Integer TYPE_PLATFORM_ADMIN = 4;
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 租户注册的实现类，
     *
     * @param tenantRegisterDto
     */
    @Override
    public void tenantRegisterCompany(TenantRegisterDto tenantRegisterDto) {
        Employee employee = tenantRegisterDto.getEmployee();
        Tenant tenant = tenantRegisterDto.getTenant();
        Long mealId = tenantRegisterDto.getMealId();

        //@todo 这里做简单的判断，在实际开发中需要做很多严谨的判断。

        if (employee == null) {
            throw new RuntimeException("请正确填写该公司管理员的信息！");
        }
        if (tenant == null) {
            throw new RuntimeException("请正确填写公司的信息！");
        }
        if (mealId == null) {
            throw new RuntimeException("请选择套餐进行购买！！");
        }
        //对参数进行判断
        if (StringUtils.isBlank(tenant.getCompanyName()) || StringUtils.isBlank(tenant.getAddress())
                || StringUtils.isBlank(tenant.getCompanyNum())) {
            throw new RuntimeException("请正确填写公司的信息！");
        }

        //调用方法存储employee
        Date date = new Date();
        tenant.setRegisterTime(date);
        baseMapper.insert(tenant);

        //存储employee
        //对，密码进行加密和加盐
        String uuid = UUID.randomUUID().toString();
        //存盐值
        employee.setSalt(uuid);
        //对密码加密加盐。
        employee.setPassword(MD5.getMD5(employee.getPassword() + uuid));
        //设置进入的时间
        employee.setInputTime(date);
        //设置管理员的类型。
        employee.setType(TenantServiceImpl.TYPE_TENANT_ADMIN);
        //设置员工的所属的租户公司，对应的id
        employee.setTenantId(tenant.getId());
        employeeMapper.insert(employee);


        //存储meanId和tenant的关联表t_tenant_meal 租户和套餐的表
        //设置过期时间,当前的时间+7天。
        Date outDays = DateUtils.addDays(date, 7);
        baseMapper.saveMeanIdWithTeantId(tenant.getId(),mealId,outDays);

    }
}
